<template>
  <a-card :bordered="false">
    <h3>数据权限管理</h3>
    <a-row style="margin-bottom: 20px;">
      <a-col :xxl="24" :xl="24" :lg="24" :sm="24">
        <span class="table-page-search-submitButtons">
          <a-button type="primary" icon="plus" @click="handleAddOrEdit(null)">添加新的部门</a-button>
        </span>
      </a-col>
    </a-row>
    <a-table bordered :pagination="false" :columns="templateColumns" :data-source="identityList" :rowKey="(record, index) => index" size="middle">
      <span slot="action" slot-scope="record">
        <a @click="handleAddOrEdit(record)">查看详情</a>
      </span>
    </a-table>
    <a-modal title="" :visible="visible" width="500px" @ok="handleSubmit" @cancel="visible = false">
      <a-form-model ref="rulesForm" :model="form" :rules="rules" layout="vertical">
        <div style="text-align: center;margin: 50px auto 20px;">请确认需要转移的身份标识</div>
        <a-form-model-item label="" prop="id">
          <a-select v-model="form.id" placeholder="请选择" show-search :filter-option="filterOption">
            <a-select-option :disabled="id == item.id" v-for="item in identityList" :value="item.id" :key="item.id">{{ item.identityName }}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>
<script>
import { identityList, userTransfer, identityDelete, identityCount } from '@/api/micromall/communityUser'
const templateColumns = [
  {
    title: '部门',
    width: 100,
    align: 'center',
    dataIndex: 'id'
  },
  {
    title: '管理员',
    width: 150,
    align: 'center',
    dataIndex: 'identityName'
  },
  {
    title: '操作',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {},
  data() {
    return {
      id: '',
      identityList: [],
      form: {},
      visible: false,
      templateColumns,
      rules: {
        id: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getIdentityList()
  },
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    // 转移
    async handleTransfer(id) {
      let count;
      try {
        count = await this.getIdentityCount(id)
      } catch (e) {
        this.$message.error(e)
      }
      if (count <= 0) {
        this.$message.error('此身份标识下已无数据！')
        return
      }
      this.visible = true
      this.id = id
    },

    // 删除
    async handleDelet(id) {
      let count;
      try {
        count = await this.getIdentityCount(id)
      } catch (e) {
        this.$message.error(e)
      }
      if (count > 0) {
        this.$message.error('此身份标识下仍有数据，请在删除模版前转移好相关用户数据！')
        return
      }
      const that = this
      this.$confirm({
        title: '此身份标识下已无数据，确认要删除吗？',
        onOk() {
          const data = {
            id
          }
          identityDelete(data).then(res => {
            if (res.code === 200) {
              that.getIdentityList()
            } else {
              that.$message.error(res.msg || res.message)
            }
          })
        },
        onCancel() {}
      })
    },

    // 查模板有无数据
    getIdentityCount(identityId) {
      const data = {
        identityId
      }
      return new Promise((resolve, reject) => {
        identityCount(data).then(res => {
          if (res.code === 200) {
            resolve(res.data)
          } else {
            this.$message.error(res.msg || res.message)
            reject()
          }
        })
      })
    },

    // 获取身份标识
    getIdentityList() {
      identityList({}).then(res => {
        if (res.code === 200) {
          this.identityList = res.data
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    // 替换特殊字符
    formatObj(values) {
      if (Object.prototype.toString.call(values) !== '[object Object]') {
        return values
      }
      let formValue = JSON.parse(JSON.stringify(values))
      Object.keys(formValue).forEach(i => {
        if ((typeof formValue[i]=='string')&&formValue[i].constructor==String) {
          formValue[i] = formValue[i].replace(/\%/g, "%25")
          formValue[i] = formValue[i].replace(/\#/g, "%23")
        } else if (Array.isArray(formValue[i])) {
          formValue[i] = formValue[i].map(e => {
           return (typeof e == 'object' && !Array.isArray(e)) ? this.formatObj(e) : e
          })
        }
      })
      return formValue
    },

    // 新增编辑
    handleAddOrEdit(e) {
      this.$router.push(`/headquarters-coupon/addDepartment`)
    },

    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.visible = false
          const data = {
            id: this.id,
            targetId: this.form.id,
            targetName: this.identityList.filter(e => e.id == this.form.id)[0].identityName
          }
          userTransfer(data).then(res => {
            if (res.code === 200) {
              if(res.data == '0') {
                this.$message.success('转移成功！')
              } else {
                this.$message.error(res.data)
              }
            } else {
              this.$message.error(res.msg || res.message)
            }
            this.form.id = ''
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.table-page-search-submitButtons {
  display: flex;
  justify-content: flex-end;
}
</style>
